package com.xxmw.transaction.service.app.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxmw.transaction.common.entity.P;
import com.xxmw.transaction.mapper.brick.BrickMapper;
import com.xxmw.transaction.model.brick.Brick;
import com.xxmw.transaction.service.app.BrickService;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author: yamoo
 * @Date: 2020-02-27 19:23
 **/
@Service
@Slf4j
public class BrickServiceImpl extends ServiceImpl<BrickMapper, Brick> implements BrickService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public P<Brick> pageList(Integer pageNum, Integer pageSize, String symbol) {
        QueryWrapper<Brick> query = new QueryWrapper<>();
        query.eq(StringUtils.isNotBlank(symbol), "symbol", symbol);
        IPage<Brick> page = new Page<>(pageNum, pageSize);
        page(page, query);
        return new P<>(page.getTotal(), page.getRecords());
    }

    @Override
    public Set<String> symbolList() {
        String value = redisTemplate.opsForValue().get("symbolList");
        if (value != null) {
            Set<String> set = JSONObject.parseObject(value, Set.class);
            return set;
        }

        QueryWrapper<Brick> wrapper = new QueryWrapper<>();
        wrapper.eq("status", Brick.Status.OPEN.value());
        List<Brick> brickList = baseMapper.selectList(wrapper);

        Set<String> symbolList = new HashSet<>();
        for (Brick brick:
                brickList) {
            symbolList.add(brick.getSymbol());
        }
        redisTemplate.opsForValue().set("symbolList", JSONObject.toJSONString(symbolList),5, TimeUnit.MINUTES);
        return symbolList;
    }

    @Override
    public List<Brick> getAvailableSymbol(String symbol) {
        QueryWrapper<Brick> wrapper = new QueryWrapper<>();
        wrapper.eq("status", Brick.Status.OPEN.value());
        wrapper.eq("symbol", symbol);
        return list(wrapper);
    }

}
